<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="模板名称" prop="formName">
        <el-input v-model="formData.formName" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="版本号" prop="formVersion">
        <el-input v-model="formData.formVersion" placeholder="请输入版本号" />
      </el-form-item>
      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效日期" prop="effectiveDate">
            <el-date-picker
              v-model="formData.effectiveDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择生效日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效日期" prop="expiryDate">
            <el-date-picker
              v-model="formData.expiryDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择失效日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-form-item label="文本内容" prop="contentText">
        <el-input
          v-model="formData.contentText"
          type="textarea"
          :rows="4"
          placeholder="请输入文本内容"
        />
      </el-form-item> -->
      <el-form-item label="状态" prop="isActive">
        <el-switch v-model="formData.isActive" />
      </el-form-item>

      <el-form-item label="HTML内容" prop="contentHtml">
        <div class="wang-editor-wrapper">
          <Toolbar
            style="border-bottom: 1px solid #dcdfe6"
            :editor="editorRef"
            :mode="mode"
          />
          <Editor
            v-model="formData.contentHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @on-created="handleCreated"
            @on-change="handleChange"
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as ConsentTemplateApi from '@/api/system/consenttemplate'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

defineOptions({ name: 'ConsentTemplateForm' })
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// wangEditor 富文本编辑器配置
const editorRef = shallowRef()
const mode = 'default' // or 'simple'

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      server: '/api/upload', // 上传接口地址
      fieldName: 'file',
      maxFileSize: 2 * 1024 * 1024, // 2M
      allowedFileTypes: ['image/*'],
      // 自定义插入图片
      customInsert(res: any, insertFn: any) {
        // res 即服务端的返回结果
        // 从 res 中找到 url alt href ，然后插入图片
        insertFn(res.url, res.alt, res.href)
      }
    }
  }
}

// // 工具栏配置
// const toolbarConfig = {
//   // 工具栏配置项
//   toolbarKeys: [
//     'headerSelect',
//     'blockquote',
//     '|',
//     'bold',
//     'underline',
//     'italic',
//     {
//       key: 'group-more-style',
//       title: '更多样式',
//       iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path></svg>',
//       menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle']
//     },
//     'color',
//     'bgColor',
//     '|',
//     'fontSize',
//     'fontFamily',
//     'lineHeight',
//     '|',
//     'bulletedList',
//     'numberedList',
//     'todo',
//     {
//       key: 'group-justify',
//       title: '对齐',
//       iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z"></path></svg>',
//       menuKeys: ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyJustify']
//     },
//     {
//       key: 'group-indent',
//       title: '缩进',
//       iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z"></path></svg>',
//       menuKeys: ['indent', 'delIndent']
//     },
//     '|',
//     'emotion',
//     'insertLink',
//     {
//       key: 'group-image',
//       title: '图片',
//       iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-168 96.01 72 128.01-96 319.97 192z"></path></svg>',
//       menuKeys: ['insertImage', 'uploadImage']
//     },
//     {
//       key: 'group-video',
//       title: '视频',
//       iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M981.184 160.096C837.568 139.456 678.848 128 512 128S186.432 139.456 42.816 160.096C15.296 267.808 0 386.848 0 512s15.264 244.16 42.816 351.904C186.464 884.544 345.152 896 512 896s325.568-11.456 469.184-32.096C1008.704 756.192 1024 637.152 1024 512s-15.264-244.16-42.816-351.904zM384 704V320l320 192-320 192z"></path></svg>',
//       menuKeys: ['insertVideo', 'uploadVideo']
//     },
//     'insertTable',
//     'codeBlock',
//     'divider',
//     '|',
//     'undo',
//     'redo',
//     '|',
//     'fullScreen'
//   ]
// }

// wangEditor 事件处理
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const handleChange = (editor: any) => {
  console.log('编辑器内容变化:', editor.getHtml())
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  formName: '',
  formVersion: '',
  contentHtml: '',
  contentText: '',
  isActive: true,
  effectiveDate: '',
  expiryDate: '',
  creator: ''
})
const formRules = reactive({
  formName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  formVersion: [{ required: true, message: '版本号不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async (type: string, row?: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (type === 'update' && row) {
    formData.value = { ...row }
    // wangEditor 通过 v-model 自动同步，无需手动设置
  }
}


defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  console.log('提交的表单数据:', formData.value) // 调试用
  
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ConsentTemplateApi.ConsentTemplateVO
    if (formType.value === 'create') {
      await ConsentTemplateApi.createConsentTemplate(data)
      message.success(t('common.createSuccess'))
    } else {
      await ConsentTemplateApi.updateConsentTemplate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    formName: '',
    formVersion: '',
    contentHtml: '',
    contentText: '',
    isActive: true,
    effectiveDate: '',
    expiryDate: '',
    creator: ''
  }
  formRef.value?.resetFields()
  // wangEditor 通过 v-model 自动同步，无需手动重置
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped>
/* wangEditor 样式调整 */
.wang-editor-wrapper {
  width: 100% !important;
  border: 1px solid #dcdfe6;
}

/* 编辑器内容区域样式 */
:deep(.wang-editor-wrapper .w-e-text-container) {
  min-height: 300px !important;
}
</style>
